#include "main.h"
#include "cmsis_os.h"
#include "fatfs.h"
#include "uart.h"
#include "key.h"
#include "oled.h"
#include "flash.h"
#include <string.h>
#include <stdio.h>

extern SPI_HandleTypeDef hspi1;
extern osTimerId KeyHandle;
extern UART_HandleTypeDef huart1;
extern I2C_HandleTypeDef hi2c2;



void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c)
{
    /* Prevent unused argument(s) compilation warning */

    Uprintf("Error");
    /* NOTE : This function should not be modified, when the callback is needed,
              the HAL_I2C_ErrorCallback can be implemented in the user file
     */
}

FRESULT scan_files (
    char* path /* Start node to be scanned (also used as work area) */
)
{
    FRESULT res;
    FILINFO fno;
    DIR dir;
    int i;
    char *fn; /* This function is assuming non-Unicode cfg. */
    uint8_t hang = 0;
#if _USE_LFN
    static char lfn[_MAX_LFN + 1];
    fno.lfname = lfn;
    fno.lfsize = sizeof lfn;
#endif
    res = f_opendir(&dir, path); /* Open the directory */
    if (res == FR_OK) {
        i = strlen(path);
        for (;;) {
            res = f_readdir(&dir, &fno); /* Read a directory item */
            if (res != FR_OK || fno.fname[0] == 0) break; /* Break on error or end of dir */
            if (fno.fname[0] == '.') continue; /* Ignore dot entry */
#if _USE_LFN
            fn = *fno.lfname ? fno.lfname : fno.fname;
#else
            fn = fno.fname;
#endif
            if (fno.fattrib & AM_DIR) { /* It is a directory */
                sprintf(&path[i], "/%s", fn);
                res = scan_files(path);
                if (res != FR_OK) break;
                path[i] = 0;
            } else { /* It is a file. */
                OLED_UPrintf(0, hang, "%s/%s\n", path, fn);
                hang += 8;
            }
        }
    }
    return res;
}

/*

        if(KeyRead(KEY0, KEY_LONG)) {
            Uprintf("FLASH_SectorErase\n");
           FLASH_SectorErase(Flash, 0x20000);
        }

        if(KeyRead(KEY0, KEY_SHORT)) {
            HAL_IRDA_Transmit_DMA(&hirda2, test, sizeof(test));
        }

        if(KeyRead(KEY1, KEY_SHORT)) {
            Uprintf("FLASH_BufferRead\n");
            Flash_WaitReady(Flash);
            FLASH_BufferRead(Flash, FlashBuf, 0x20000, 4096);
            HAL_Delay(500);

            for( i = 0; i < 4096; i++) {
                if(FlashBuf[i] != (i & 0xFF)) break;
            }
            Uprintf("i : %d\n", i);
        }



*/

